package com.fanjun.learning.multithread.Read_Write_Lock_Pattern;

/**
 * <p>自定义读写锁,来控制并发访问</p>
 */
public final class ReadWriteLock {
    // 正在读的线程数
    private int readingReaders = 0;
    // 正在等待写的线程数
    private int waitingWriters = 0;
    // 正在写的线程数
    private int writingWriters = 0;
    // 是否优先写
    private boolean preferWriter = true;

    public synchronized void readLock() throws InterruptedException {
        while (writingWriters > 0 || (waitingWriters > 0 && preferWriter)) {
            wait();
        }
        readingReaders++;
    }

    public synchronized void readUnlock() {
        readingReaders--;
        preferWriter = true;
        notifyAll();
    }

    public synchronized void writeLock() {
        waitingWriters++;
        while (readingReaders > 0 || writingWriters > 0){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                waitingWriters--;
            }
        }
        writingWriters++;
    }

    public synchronized void writeUnlock() {
        writingWriters--;
        preferWriter = false;
        notifyAll();
    }
}
